package com.gy.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gy.controller.common.UploadController;
import com.gy.controller.common.UserHolder;
import com.gy.entity.result.Other;
import com.gy.entity.result.PersonalAward;
import com.gy.mapper.PersonalAwardMapper;
import com.gy.query.PersonalAwardQuery;
import com.gy.result.Result;
import com.gy.service.PersonalAwardService;
import com.gy.service.UserService;
import com.gy.vo.PageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class PersonalAwardImpl extends ServiceImpl<PersonalAwardMapper, PersonalAward> implements PersonalAwardService {
    @Autowired
    private UploadController uploadController;

    @Autowired
    private PersonalAwardMapper personalAwardMapper;
    @Autowired
    private UserService userService;

        /**
         * 根据openid分页查看某个人的个人获奖信息
         */
        @Override
        public Result<PageVO<PersonalAward>> getPersonalAward(PersonalAwardQuery personalAwardQuery) {
            Long openId = UserHolder.getUser().getUserId();
            if (openId == null) {
                return Result.error("用户登录信息异常");
            }
            Page<PersonalAward> page = Page.of(personalAwardQuery.getPageNo(), personalAwardQuery.getPageSize());
            //排序条件
            if (!personalAwardQuery.getSortBy().isEmpty() || personalAwardQuery.getIsAsc() != null) {
                page.addOrder(new OrderItem(personalAwardQuery.getSortBy(), personalAwardQuery.getIsAsc()));
            } else {
                // 为空，默认按照出版时间排序
                page.addOrder(new OrderItem("id", false));
            }
            //构建查询条件
            LambdaQueryChainWrapper<PersonalAward> queryWrapper = lambdaQuery()
                    .eq(openId != null, PersonalAward::getUserId, openId);

            // 仅在开始日期和结束日期不为空且有效时添加 between 条件
            if (personalAwardQuery.getStartDate() != null && personalAwardQuery.getEndDate() != null) {
                try {
                    Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse(personalAwardQuery.getStartDate());
                    Date endDate = new SimpleDateFormat("yyyy-MM-dd").parse(personalAwardQuery.getEndDate());
                    queryWrapper.between(PersonalAward::getAwardTime, startDate, endDate);
                } catch (ParseException e) {
                    System.err.println("Invalid date format: " + e.getMessage());
                }
            }

            //添加获奖名次分页查询参数
            if (personalAwardQuery.getAwardLevel() != null) {
                queryWrapper.eq(PersonalAward::getAwardLevel, personalAwardQuery.getAwardLevel());
            }
            Page<PersonalAward> personalAwardPage = queryWrapper.page(page);
            //封装VO结果
            PageVO<PersonalAward> vo = new PageVO<>();
            vo.setTotal(personalAwardPage.getTotal());
            vo.setPages(personalAwardPage.getPages());
            List<PersonalAward> records = personalAwardPage.getRecords();
            if (CollUtil.isEmpty(records)) {
                vo.setList(Collections.emptyList());
            } else {
                vo.setList(records);
            }
            return Result.success(vo);
        }

    @Override
    @Transactional
    public Result removePersonalAward(Long id) {
        PersonalAward personalAward = getById(id);
        if (personalAward == null) {
            return Result.error("个人奖项信息未找到");
        }

        String pdfPath = personalAward.getPdfPath();

        // 检查 pdfPath 是否为空
        if (pdfPath != null && !pdfPath.isEmpty()) {
            try {
                uploadController.deleteFile(pdfPath);
            } catch (Exception e) {
                return Result.error("删除文件失败");
            }
        } else {
            log.warn("pdfPath 为空，无需删除文件");
        }

        boolean removed = removeById(id);
        if (!removed) {
            return Result.error("删除个人奖项信息失败");
        }
        userService.decrementUserAwardPersonalCount();
        return Result.success("个人奖项信息删除成功");
    }

    @Override
    public PersonalAward getPersonalAwardById(Long id) {
            if (id==null)
            {
                return null;
            }
        return personalAwardMapper.selectPersonalAwardById(id);
    }

    @Override
    public Result updatePersonalAward(PersonalAward personalAward) {
        // 参数验证
        if (personalAward == null) {
            return Result.error("个人奖项信息不能为空");
        }
        if (personalAward.getId() == null) {
            return Result.error("个人奖项ID不能为空");
        }

        try {
            int affectedRows = personalAwardMapper.updatePersonalAward(personalAward);
            if (affectedRows > 0) {
                return Result.success(personalAward);
            } else {
                return Result.error("未找到对应的个人奖项信息进行更新");
            }
        } catch (Exception e) {
            // 记录日志
            log.error("更新个人奖项信息时发生异常", e);
            return Result.error("更新个人奖项信息失败");
        }
    }

    @Override
    @Transactional
    public Result savePersonalAward(PersonalAward personalAward) {
        if (personalAward == null) {
            log.warn("传入的个人奖项对象为空");
            return Result.error("个人奖项对象不能为空");
        }
        try {
            // 设置用户 ID
            personalAward.setUserId(UserHolder.getUser().getUserId());

            boolean save = personalAwardMapper.savePersonalAward(personalAward);
            if (!save) {
                return Result.error("新增失败");
            }
            userService.incrementUserAwardPersonalCount();

            return Result.success("新增成功");
        } catch (Exception e) {
            // 记录异常日志
            log.error("保存个人奖项时发生异常", e);
            return Result.error("系统错误，请稍后再试");
        }
    }

    @Override
    public Result getPersonalAwardByIds(Long[] ids) {
            if (ids != null && ids.length > 0) {
                List<PersonalAward> personalAwardList = personalAwardMapper.selectPersonalAwardBatchIds(Arrays.asList(ids));
                return Result.success(personalAwardList);
            }
            return null;
    }


}
